package com.quanquan.store.service;

import com.quanquan.store.entity.Concern;
import com.quanquan.store.repository.ConcernRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.UUIDGenerator;

import java.util.Date;
import java.util.List;

/**
 * @ClassName:ConcernService
 * @Description:TODO
 * @Author:xiongjunbao
 * @Date:2019/3/20 17:36
 * @Version 1.0
 */
@Service
public class ConcernService {

    @Autowired
    private ConcernRepository concernRepository;

    /**
     * 用户关注商户列表
     *
     * @param userId
     * @param page
     * @param size
     * @return
     */
    public List<Concern> queryByUserId(String userId, Integer page, Integer size) {
        List<Concern> concernList = concernRepository.queryByUserId(userId, page * size, size, 0);
        return concernList;
    }

    /**
     * 关注店铺
     *
     * @param userId
     * @param storeId
     * @return
     */
    public Integer concern(String userId, String storeId) {
        Concern concern = concernRepository.queryByUserIdAndStoreId(userId, storeId);
        Date date = new Date();
        if (concern != null) {
            //查询表中是否有过记录，若有之前的取关纪录重新设置为关注，节省数据库开销
            if (concern.getStatusRemove() == 1) {
                concern.setStatusRemove(0);
                concern.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                concernRepository.saveAndFlush(concern);
                return concern.getStatusRemove();
            } else {
                concern.setStatusRemove(1);
                concern.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                concernRepository.saveAndFlush(concern);
                return concern.getStatusRemove();
            }
        }
        Concern localConcern = new Concern();
        localConcern.setStatusRemove(0);
        localConcern.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        localConcern.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        localConcern.setStatusShow(0);
        localConcern.setStoreId(storeId);
        localConcern.setUserId(userId);
        localConcern.setId(UUIDGenerator.getUUID());
        concernRepository.saveAndFlush(localConcern);
        return localConcern.getStatusRemove();
    }




}
